import { login, getUserInfo, getUserDetailById } from '@/api/user.js'
import { getToken, setToken, removeToken, setTokenTime } from '@/utils/auth.js'
import { resetRouter, constantRoutes } from '@/router'

const state = {
  // 储存用户token
  token: getToken(),
  // 保存用户信息
  userInfo: {},
  // 左侧菜单数据
  menu: [],
  point: {
    POINTS_USER_ADD: 'point-user-add',
    POINTS_USER_UPDATE: 'point-user-update',
    POINTS_USER_DELETE: 'point-user-delete'
  }
}
const mutations = {
  // 保存token
  setToken(state, payload) {
    state.token = payload
    setToken(payload)
  },
  // 保存用户信息
  setUserInfo(state, payload) {
    state.userInfo = payload
  },
  // 清空token
  clearToken(state) {
    // 清空vuex的token
    state.token = null
    // 清空本地储存的token
    removeToken()
  },
  // 清空用户的信息
  clearUserInfo() {
    // 清空用户信息数据
    state.userInfo = {}
  },
  // 用户退出登录
  logout() {
    // mutation中的this是store
    this.commit('user/clearToken')
    this.commit('user/clearUserInfo')
    this.commit('user/setMenu', [])
    // 退出登录清空路由规则
    resetRouter()
  },
  // 保存路由规则映射左侧菜单
  setMenu(state, payload) {
    state.menu = [...constantRoutes, ...payload]
  }
}
const actions = {
  // 登录请求
  async login(context, data) {
    // 登录接口请求调用                                                                                    用
    const res = await login(data)
    console.log(res)
    context.commit('setToken', res)
    // 请求成功之后保存时间戳
    setTokenTime()
  },
  // 获取用户资料
  async getUserInfoo(context) {
    const userId = await getUserInfo()
    // 获取用户详细信息
    const userInfo = await getUserDetailById(userId.userId)
    // console.log(userInfo)
    // 保存用户详细信息
    context.commit('setUserInfo', { ...userId, ...userInfo })
    return userId
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}

